﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FCBLL;
using FCDAL;
using FCModel;
using System.IO;
using System.Data;
using MiscLib;
using System.Text;

namespace FileConverter.IQC
{
    public partial class Parameter : System.Web.UI.Page
    {
        string TestType;
        string dataFormatType;

        protected void Page_Load(object sender, EventArgs e)
        {
            TestType = Request.Params["TestType"].ToString();
            dataFormatType = new BaseRepositoryBLL<bas_TestType>().LoadEntities(p => p.testType.Equals(TestType, StringComparison.OrdinalIgnoreCase)).FirstOrDefault().dataFormatType;
            lblInfo.Text = "";
            if (!Page.IsPostBack)
            {
                DropDownList1.DataSource = new BaseRepositoryBLL<ParameterRange>().LoadEntities(p => p.partNo != null && p.partNo != "All").Select(p => p.partNo).Distinct().ToList<string>();
                DropDownList1.DataBind();
                DropDownList1.Items.Insert(0, new ListItem("All"));
                if (TestType == "Access")
                {
                    Label1.Visible = true;
                    tb_GR_NO.Visible = true;
                }
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string logPath = Server.MapPath("~/Excel/");
            if (FileUpload1.PostedFile.FileName == "" || FileUpload1.PostedFile.InputStream.Length < 1)
            {
                lblInfo.Text = "没有指定文件.";
            }
            else
            {
                try
                {
                    //根据testType获取dataFormatType
                    string fileExt = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
                    string FileName = new FileInfo(FileUpload1.PostedFile.FileName).Name;
                    IFormatBLL ifbll = null;
                    string[] arrFile = null;

                    //CommonBLL.WriteLog(logPath, "\r\n");
                    //CommonBLL.WriteLog(logPath, "进入程序");
                    if (fileExt.Contains(".xls"))// == ".xlsx" || fileExt == ".xls")
                    {
                        string fileName = Guid.NewGuid().ToString() + fileExt;
                        if (!Directory.Exists(Server.MapPath("~/Excel/")))
                        {
                            Directory.CreateDirectory(Server.MapPath("~/Excel/"));
                        }
                        FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Excel/") + fileName);
                        DataSet ds = CommonBLL.ExcelToDS(Server.MapPath("~/Excel/") + fileName);

                        if (System.IO.File.Exists(Server.MapPath("~/Excel/") + fileName))
                        {
                            File.Delete(Server.MapPath("~/Excel/") + fileName);
                        }
                        arrFile = CommonBLL.DataSetToStringArray(ds);
                    }
                    else if (fileExt.Contains(".mdb"))
                    {
                        string fileName = Guid.NewGuid().ToString() + fileExt;
                        string gr_no = tb_GR_NO.Text;
                        if (string.IsNullOrWhiteSpace(gr_no))
                        {
                            lblInfo.Text = "请输入GR号";
                            return;
                        }
                        if (!Directory.Exists(Server.MapPath("~/Access/")))
                        {
                            Directory.CreateDirectory(Server.MapPath("~/Access/"));
                        }
                        FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Access/") + fileName);
                        bool success = true;
                        DataSet ds = CommonBLL.AccessToDS("report", gr_no, Server.MapPath("~/Access/") + fileName, ref success);
                        if (System.IO.File.Exists(Server.MapPath("~/Access/") + fileName))
                        {
                            File.Delete(Server.MapPath("~/Access/") + fileName);
                        }
                        arrFile = CommonBLL.DataSetToStringArray(ds);
                    }
                    else if (fileExt == ".txt")
                    {
                        byte[] byFile = new byte[FileUpload1.PostedFile.ContentLength];
                        FileUpload1.PostedFile.InputStream.Read(byFile, 0, FileUpload1.PostedFile.ContentLength);
                        FileUpload1.PostedFile.InputStream.Close();
                        string strFile = System.Text.Encoding.ASCII.GetString(byFile);
                        arrFile = strFile.Split('\r');
                        //   CommonBLL.WriteLog(logPath, "读取成功");
                    }
                    if (dataFormatType == "SmartScopeFormatBLL")
                    {
                        ifbll = new SmartScopeFormatBLL();
                    }
                    else if (dataFormatType == "TableFormatBLL")
                    {
                        ifbll = new TableFormatBLL();
                    }
                    else if (dataFormatType == "cmmBLL")
                    {
                        ifbll = new cmmBll();
                    }

                    IList<ParameterDao> listSSD = ifbll.AnalysisFile(arrFile, TestType);
                    //    CommonBLL.WriteLog(logPath, "分析完成");
                    lblInfo.Text = "分析完成";
                    DataTable dt = CommonBLL.ParameterDaoToDataTable(listSSD, DropDownList1.Text);
                    //      CommonBLL.WriteLog(logPath, "生成DT");
                    string path = Server.MapPath("~/Excel/");
                    ExporttoExcel(dt, path, DropDownList1.Text, FileName.Split('.')[0], logPath);

                    //  CommonBLL.WriteLog(logPath, "转换成EXCEL，成功下载");
                }
                catch (Exception err)
                {
                    lblInfo.Text = err.Message;
                    CommonBLL.WriteLog(logPath, err.Message);
                }
            }
        }
        private void ExporttoExcel(DataTable dt, string path, string partNo, string FileName, string logPath)
        {
            ExcelExport.OutputExcel(dt.DefaultView, path, partNo, FileName, HttpContext.Current.Response, Server, logPath);
        }
    }
}